from exchange import Exchange
from time import gmtime, strftime, time

##################################################
# How to use the Exchange class

def main():

    # The market

    EVENT_TYPE_ID = 2378961 # Politics
    EXCHANGE_ID = 1
    MARKET_ID = 2839627 # 2008 U.S. Presidential Election - Winning Party
    SELECTION_ID = 1171581 # Democrats
    
    # How to call login

    username = raw_input("username: ")
    password = raw_input("password: ")

    exchange = Exchange()
    exchange.login(username, password)

    # How to call get_account_funds
    
    funds = exchange.get_account_funds(Exchange.EXCHANGE_UK)
    print "available balance on exchange %s = %s" % (EXCHANGE_ID, funds._availBalance)

    # How to call get_active_event_types/get_all_event_types

    for event_type in exchange.get_all_event_types():
        print "%s (id = %s)" % (event_type._name, event_type._id)

    # How to call get_events
    
    events, market_summaries = exchange.get_events(7)
    for event in events:
        print "%s (id = %s)" % (event._eventName, event._eventId)
    for market_summary in market_summaries:
        print "%s (id = %s)" % (market_summary._marketName, market_summary._marketId)

    events, market_summaries = exchange.get_events(13)
    for event in events:
        print "%s (id = %s)" % (event._eventName, event._eventId)
    for market_summary in market_summaries:
        print "%s (id = %s)" % (market_summary._marketName, market_summary._marketId)
        
    # How to call get_market
    
    market = exchange.get_market(EXCHANGE_ID, MARKET_ID)
    print "market = %s (id = %s)" % (market._name, market._marketId)
    print "market status = %s" % (market._marketStatus)
    print "market time = %s" % (strftime("%x %X", market._marketTime))
    print "bsp market = %s" % (market._bspMarket)
    print "runners:"
    for runner in market._runners._Runner:
        print "  %s" % (runner._name)

    # How to call get_market_prices

    market_prices = exchange.get_market_prices(EXCHANGE_ID, MARKET_ID)
    for runner_prices in market_prices._runnerPrices._RunnerPrices:
        print "prices for %s:" % (Exchange.find_runner(market, runner_prices._selectionId)._name)
        print "  back:"
        for price in runner_prices._bestPricesToBack._Price:
            print "    %s = %s (available = %s)" % (price._depth, price._price, price._amountAvailable)
        print "  lay:"
        for price in runner_prices._bestPricesToLay._Price:
            print "    %s = %s (available = %s)" % (price._depth, price._price, price._amountAvailable)

    # How to call get_market_traded_volume
        
    print "traded:"
    infos = exchange.get_market_traded_volume(EXCHANGE_ID, MARKET_ID, SELECTION_ID)
    for info in infos:
        print "  %s @ %s" % (info._totalMatchedAmount, info._odds)

    # How to call get_detail_available_mkt_depth

    print "available:"
    infos = exchange.get_detail_available_mkt_depth(EXCHANGE_ID, MARKET_ID, SELECTION_ID)
    for info in infos:
        if info._totalAvailableBackAmount > 0:
            print "  %s to back @ %s" % (info._totalAvailableBackAmount, info._odds)
        if info._totalAvailableLayAmount > 0:
            print "  %s to lay @ %s" % (info._totalAvailableLayAmount, info._odds)
    
    # Place, update and cancel a bet that will not be matched

    allow = raw_input("allow placement (y/n)?: ")
    if allow.strip() != "y":
        return

    # How to call place_bets
    
    place_bets = []
    place_bets.append(Exchange.new_place_bet(MARKET_ID, SELECTION_ID, "L", 1.01, Exchange.MINIMUM_SIZE + 1))
    place_results = exchange.place_bets(EXCHANGE_ID, place_bets)

    print "placed bets:"
    for result in place_results:
        print "  %s (id = %s)" % (result._resultCode, result._betId)

    # Enumerate the unmatched bets

    enumerate_unmatched_bets(exchange, EXCHANGE_ID, MARKET_ID)

    # How to call update_bets

    id = place_results[0]._betId
    b = place_bets[0]
    update_bets = []
    update_bets.append(Exchange.new_update_bet(id, b._price, b._price, b._size, b._size - 1.0))
    update_results = exchange.update_bets(EXCHANGE_ID, update_bets)

    print "updated bets:"
    for result in update_results:
        print "  %s (id = %s; size cancelled = %s)" % (result._resultCode, result._betId, result._sizeCancelled)

    # Enumerate the unmatched bets

    enumerate_unmatched_bets(exchange, EXCHANGE_ID, MARKET_ID)

    # How to call cancel_bets

    cancel_bets = []
    cancel_bets.append(Exchange.new_cancel_bet(id))
    cancel_results = exchange.cancel_bets(EXCHANGE_ID, cancel_bets)

    print "cancelled bets:"
    for result in cancel_results:
        print "  %s (id = %s; size cancelled = %s)" % (result._resultCode, result._betId, result._sizeCancelled)

    # Enumerate the unmatched bets

    enumerate_unmatched_bets(exchange, EXCHANGE_ID, MARKET_ID)
    
    # How to call get_bet_history and page through the results

    from_date = gmtime(time() - (90 * 24 * 60 * 60))
    to_date = gmtime(time())

    historic_bets = []
    print "some historic bets:"
    pager = Exchange.Pager()
    # while not pager.is_finished(): # Should loop here, but throttling could raise an error
    historic_bets.extend(exchange.get_bet_history(EXCHANGE_ID, [7], "S", from_date, to_date, pager))
    if len(historic_bets) > 0:
        for bet in historic_bets:
            print "  bet (id = %s):" % (bet._betId)
            print "    type = %s" % (bet._betType)
            print "    category = %s" % (bet._betCategoryType)
            print "    persistence = %s" % (bet._betPersistenceType)
            print "    price = %s" % (bet._price)
            print "    remaining = %s" % (bet._remainingSize)
            print "    status = %s" % (bet._betStatus)
    else:
        print "  no historic bets"
    
    # How to call logout

    exchange.logout()

##################################################
# How to call get_current_bets and page through the results

def enumerate_unmatched_bets(exchange, exchange_id, market_id):
    current_bets = []
    print "current unmatched bets:"
    pager = Exchange.Pager()
    while not pager.is_finished():
      current_bets.extend(exchange.get_current_bets(exchange_id, "U", pager, market_id=market_id, order_by="PLACED_DATE"))
    if len(current_bets) > 0:
        for bet in current_bets:
            print "  bet (id = %s):" % (bet._betId)
            print "    type = %s" % (bet._betType)
            print "    category = %s" % (bet._betCategoryType)
            print "    persistence = %s" % (bet._betPersistenceType)
            print "    price = %s" % (bet._price)
            print "    remaining = %s" % (bet._remainingSize)
            print "    status = %s" % (bet._betStatus)
    else:
        print "  no unmatched bets in market"

if __name__ == "__main__":
    main()